import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/**
 * 自定义的 switch 可自定义大小
 */
import 'package:flutter/material.dart';

class CustomSwitch extends StatefulWidget {
  final bool value;
  final ValueChanged<bool>? onChanged;
  final Color trueColor;
  final Color falseColor;
  final double size;

  CustomSwitch({
    required this.value,
    this.onChanged,
    this.trueColor = Colors.blue,
    this.falseColor = Colors.grey,
    this.size = 30.0,
  });

  @override
  _CustomSwitchState createState() => _CustomSwitchState();
}

class _CustomSwitchState extends State<CustomSwitch> {
  bool _value = false;

  @override
  void initState() {
    _value = widget.value;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        setState(() {
          _value = !_value;
          if (widget.onChanged != null) {
            widget.onChanged!(_value);
          }
        });
      },
      child: Container(
        width: widget.size,
        height: widget.size / 2,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(widget.size / 2),
          color: _value ? widget.trueColor : widget.falseColor,
        ),
        child: Padding(
          padding: EdgeInsets.all(widget.size / 20),
          child: Align(
            alignment: _value ? Alignment.centerRight : Alignment.centerLeft,
            child: Container(
              width: widget.size / 2 - widget.size / 10,
              height: widget.size / 2 - widget.size / 10,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                color: Colors.white,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
